import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { eventTrack } from '@/utils/track';
import { Form, Card, message } from 'antd';
import moment from 'moment';
import pageTabUtil from '@/utils/pageTabUtil';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { formItemLayout } from '@/components/UserForm';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageRouter from '@/components/PageRouter/PageRouter';
import { uploadFileToServer } from '@/utils/utils';
import useParseResume from '@/hooks/useParseResume';

import TalentPoolForm from './Components/TalentPoolForm';

const AddTalentPool = ({ dispatch, form, user, talentPool }) => {
    const User = user.currentUser;
    const candidate = talentPool.candidateInfo; // 候选人信息
    const [submitLoading, setsubmitLoading] = useState(false);
    // 文件信息
    const [showFileList, setShowFileList] = useState([]);
    const [uploadResource, setUploadResource] = useState(null);
    const { resumeData, setFormFields, fetchResumeData } = useParseResume({
        dictionary: { sexType: talentPool.candidateSexTypeList, agreeType: talentPool.candidateAgreeTypeList },
        form
    });

    /**
     * 获取个人数据
     */
    const getUserInfo = () => {
        dispatch({
            type: 'userInfo/getUserInfo'
        });
    };
    // 表单提交
    const saveInfo = values => {
        setsubmitLoading(true);
        dispatch({
            type: 'talentPool/saveorupdate',
            payload: values,
            callback: res => {
                if (res.code === 10000) {
                    message.success(res.msg);
                    pageTabUtil.goBack();
                } else {
                    message.error(res.msg);
                }
                setsubmitLoading(false);
            }
        });
    };
    const setFileResource = (showFileListReturn, uploadResourceReturn) => {
        setShowFileList(showFileListReturn);
        setUploadResource(uploadResourceReturn);

        const uploadedFile = [...showFileListReturn].pop();
        if (uploadedFile) {
            const { type, status, originFileObj } = uploadedFile;
            if (
                status === 'done' &&
                type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            ) {
                uploadFileToServer({
                    requestUrl: '/api/oa/v1/stream/talent/importdata',
                    originFileObj
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 10000) {
                            fetchResumeData(originFileObj.name);
                        }
                    });
            }
        }
    };
    const returnUp = () => {
        pageTabUtil.goBack();
    };
    /**
     * 表单提交
     */
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFieldsAndScroll(async (err, values) => {
            console.log(values, 'values');
            if (!err) {
                const result = {
                    id: candidate.id,
                    talentName: candidate.talentName,
                    talentLeaderId: candidate.talentLeaderId,
                    talentPhone: candidate.talentPhone,
                    insertDate: candidate.insertDate
                };
                // 附件需要特殊处理
                const resourceRelationArr = [];
                if (uploadResource) {
                    resourceRelationArr.push(uploadResource);
                }
                const originData = form.getFieldsValue();
                // 下面日期判断直接使用招聘登记表的提交判断
                Object.keys(originData).forEach(key => {
                    const arr = key.split('_');
                    if (originData[key] || originData[key] === 0) {
                        if (arr[2]) {
                            if (!result[arr[0]]) {
                                result[arr[0]] = [];
                            }
                            if (!result[arr[0]][Number(arr[2])]) {
                                result[arr[0]][Number(arr[2])] = {};
                            }
                            if (originData[key] || originData[key] === 0) {
                                if (arr[1] === 'dateRange') {
                                    if (originData[key][0]) {
                                        result[arr[0]][Number(arr[2])].startTime = moment(originData[key][0]).format(
                                            'YYYY-MM-01'
                                        );
                                        result[arr[0]][Number(arr[2])].endTime = moment(originData[key][1]).format(
                                            'YYYY-MM-01'
                                        );
                                    }
                                } else if (originData[key] instanceof moment) {
                                    result[arr[0]][Number(arr[2])][arr[1]] = moment(originData[key]).format(
                                        'YYYY-MM-DD'
                                    );
                                } else {
                                    result[arr[0]][Number(arr[2])][arr[1]] = originData[key];
                                }
                            }
                        } else if (Array.isArray(originData[key])) {
                            result[arr[0]] = originData[key].join(',');
                        } else if (originData[key] instanceof moment) {
                            result[arr[0]] = moment(originData[key]).format('YYYY-MM-DD');
                        } else {
                            result[arr[0]] = originData[key];
                        }
                    }
                });
                const haveObjInArr = arrData => {
                    let ret = false;
                    for (let i = 0; i < arrData.length; i += 1) {
                        if (typeof arrData[i] === 'object') {
                            ret = true;
                            break;
                        }
                    }
                    return ret;
                };
                Object.keys(result).forEach(rKey => {
                    if (Array.isArray(result[rKey]) && haveObjInArr(result[rKey])) {
                        const newArr = [];
                        result[rKey].forEach(item => {
                            if (item && Object.keys(item).length > 0) {
                                const { id, deleteFlag, ...otherField } = item;
                                const validField = Object.keys(otherField).find(field => {
                                    if (field) {
                                        return true;
                                    }
                                    return false;
                                });
                                newArr.push({ ...item, deleteFlag: validField ? 0 : 1 });
                            }
                        });
                        result[rKey] = newArr;
                    }
                });
                const payload = {
                    ...result,
                    resourceRelation: resourceRelationArr,
                    talentNationalArea: result.talentNationalArea.split(','),
                    address: result.address.split(','),
                    talentBirth: result.talentBirth === '' ? null : result.talentBirth
                };
                console.log('===============================================>payload', payload);
                saveInfo(payload);
                eventTrack({
                    eventName: 'personal_my_recruit_talentPool_add_submit_click',
                    eventProps: { label: '添加人才简历-提交', status: 0 }
                });
            } else {
                eventTrack({
                    eventName: 'personal_my_recruit_talentPool_add_submit_click',
                    eventProps: { label: '添加人才简历-提交', status: 1, error_info: JSON.stringify(err) }
                });
            }
        });
    };
    const getDict = () => {
        dispatch({
            type: 'talentPool/getDict'
        });
    };
    useEffect(() => {
        getUserInfo();
        getDict();
    }, []);
    useEffect(() => {
        const fieldMap = {
            mobile: 'talentPhone',
            sex: 'talentSex',
            employeeName: 'talentName',
            mail: 'talentEmail',
            birthdayTime: 'talentBirth',
            highestDegree: 'talentDegree',
            major: 'talentProfessional',
            college: 'talentGraduateSchool',
            graduateTime: 'talentGraduate'
            // lastCompany: 'lastCompany',
            // lastPost: 'lastPost'
        };
        setFormFields(fieldMap);
    }, [resumeData]);
    return (
        <PageHeaderWrapper>
            <PageRouter type="myrecruit" activePath="/personal/portal/recruit/talentPool">
                <Form layout="horizontal" {...formItemLayout} onSubmit={handleSubmit}>
                    <Card bordered={false}>
                        <div className="form-Wrap">
                            <TalentPoolForm
                                isEdit
                                required={false}
                                enterType="add"
                                onReturn={() => {
                                    eventTrack({
                                        eventName: 'personal_my_recruit_talentPool_add_cancel_click',
                                        eventProps: { label: '添加人才简历-取消' }
                                    });
                                    returnUp();
                                }}
                                showFileList={showFileList}
                                uploadResource={uploadResource}
                                onSetFileResource={setFileResource}
                                form={form}
                                user={User}
                                candidate={candidate}
                                companyId={User.companyId}
                                submitLoading={submitLoading}
                            />
                        </div>
                    </Card>
                </Form>
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, user, talentPool }) => ({
        loading: loading.models,
        user,
        talentPool
    }))(Form.create()(AddTalentPool))
);
